<template>
  <div class="app-container pagebox">
    <div class="bg" style="margin-bottom: 20px">
      <a-form layout="inline" :form="form" @submit="handleSubmit" style="padding: 20px 20px">
        <a-form-item>
          <a-date-picker :disabled="disabledStatus" @change="onChangestart" placeholder="开始时间" />
        </a-form-item>
        <a-form-item>
          <a-date-picker :disabled="disabledStatus" @change="onChangeEnd" placeholder="结束时间" />
        </a-form-item>
        <a-form-item>
          <a-input :disabled="disabledStatus" placeholder="报警号/报警内容" v-model="form.alarmNum" />
        </a-form-item>
        <a-form-item v-if="roleId == 3">
          <a-input :disabled="disabledStatus" placeholder="模糊查询" v-model="form.param" />
        </a-form-item>
        <!-- <a-form-item>
          <a-input placeholder="设备编号" v-model="form.alarmNum" />
        </a-form-item> -->
        <a-form-item v-if="roleId != 1">
          <a-tree-select
            v-model="form.compId"
            style="width:200px"
            allowClear
            :disabled="disabledStatus"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择公司"
            tree-default-expand-all
          >
            <a-tree-select-node
              :key="item.macfacid"
              :value="item.macfacid"
              :title="item.macfacName"
              v-for="item in macfacData"
            >
              <a-tree-select-node :key="com.compid" :value="com.compid" :title="com.name" v-for="com in item.company" />
            </a-tree-select-node>
          </a-tree-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" style="margin-right: 10px" @click="handlequery(1)">
            查询
          </a-button>
        </a-form-item>
        <a-form-item>
          <ExportFile :fetch="getDownloadData" :fields="jsonFields" name="调机历史.xls">
            <a-button type="primary" style="margin-right: 10px" :loading="iconLoading">
              导出
            </a-button>
          </ExportFile>
        </a-form-item>
      </a-form>
    </div>

    <div class="bg">
      <div class="alarmStyle">
        <ul>
          <li style="border: 1px solid #ff3535; color: #ff3535" @click="clickalarmType('1')">
            一级报警
            <a-icon
              v-if="form.alarmType.indexOf('1') >= 0"
              class="liicon"
              type="check-square"
              theme="filled"
              style="color: #ff3535"
            />
          </li>
          <li style="border: 1px solid #ff7865; color: #ff7865" @click="clickalarmType(2)">
            二级报警
            <a-icon
              v-if="form.alarmType.indexOf('2') >= 0"
              class="liicon"
              type="check-square"
              theme="filled"
              style="color: #ff7865"
            />
          </li>
          <li style="border: 1px solid #ffbb00; color: #ffbb00" @click="clickalarmType(3)">
            三级报警
            <a-icon
              class="liicon"
              v-if="form.alarmType.indexOf('3') >= 0"
              type="check-square"
              theme="filled"
              style="color: #ffbb00"
            />
          </li>
          <li style="border: 1px solid #f8d77e; color: #f8d77e" @click="clickalarmType(4)">
            系统提示信息
            <a-icon
              v-if="form.alarmType.indexOf('4') >= 0"
              class="liicon"
              type="check-square"
              theme="filled"
              style="color: #f8d77e"
            />
          </li>
        </ul>
      </div>
      <div>
        <a-table
          :loading="Loading"
          :pagination="false"
          :columns="columns"
          :data-source="data"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
        >
          <span
            slot="alarmNum"
            slot-scope="text, record"
            :style="{
              'background-color': colorList[record.alarmtype - 1],
              color: '#fff',
              padding: '0 4px',
            }"
          >
            {{ text }}
          </span>
          <span slot="manager" slot-scope="text, record">{{ text }}{{ record.phone }}</span>
          <span slot="conduct" slot-scope="text, record" @click="toProcess(record)">
            <a-icon type="ellipsis" style="color: #289ef6; font-size: 30px; font-weight: bold" />
          </span>
        </a-table>
        <div style="padding: 20px">
          <a-pagination
            size="small"
            v-model="form.page"
            :total="total"
            :show-total="(total) => `一共 ${total} 条`"
            @change="changepage"
          />
        </div>
      </div>
    </div>
    <a-modal v-model="visible" title="处理报警" ok-text="确认" cancel-text="取消" @ok="hideModal" width="20%">
      <a-select  :getPopupContainer="(triggerNode) => triggerNode.parentNode" placeholder="请选择处理方式" style="width: 200px" v-model="resolveMethod">
        <a-select-option :value="item" v-for="(item, index) in handlingList" :key="index">
          {{ item }}
        </a-select-option>
      </a-select>
    </a-modal>
  </div>
</template>
<script>
//
const columns = [
  {
    title: '报警时间',
    dataIndex: 'uploadtime',
    key: 'uploadtime',
  },
  {
    title: '报警号',
    dataIndex: 'alarmNum',
    key: 'alarmNum',
    scopedSlots: { customRender: 'alarmNum' },
  },
  {
    title: '报警内容',
    dataIndex: 'alarmdata',
    key: 'alarmdata',
  },
  {
    title: '设备编号',
    dataIndex: 'macnumb',
    key: 'macnumb',
  },
  {
    title: '厂家',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '联系人',
    dataIndex: 'manager',
    scopedSlots: { customRender: 'manager' },
    key: 'manager',
  },
  {
    title: '联系方式',
    dataIndex: 'phone',
    key: 'phone',
    colSpan: 0,
  },
  {
    title: '处理',
    dataIndex: 'conduct',
    key: 'conduct',
    scopedSlots: { customRender: 'conduct' },
  },
  {
    title: '处理方式',
    dataIndex: 'resolveMethod',
    key: 'resolveMethod',
    scopedSlots: { customRender: 'resolveMethod' },
  },
  {
    title: '处理时间',
    dataIndex: 'resolveTime',
    key: 'resolveTime',
  },
];
function buildJsonFields(lists) {
  let jsonFields = {};
  lists.forEach((item, index) => {
    if (item.dataIndex != 'conduct') {
      jsonFields[item.title] = item.dataIndex;
    }
  });

  return jsonFields;
}
let handlingList = [
  '客户误操作',
  '车间供电问题',
  '客户接地不规范',
  '客户自行处理',
  '硬件故障',
  '软件故障',
  '安排现场技术服务',
  '其他',
];
let colorList = ['#FF3535', '#FF7865', '#FFBB00', '#f8d77e'];
import api from '@/api/statisticalForm.js';
import eapi from '@/api/equipment.js';
import { debounce } from '@/unit/debounce.js';
import { computeData } from '@/unit/tool';
export default {
  data() {
    return {
      data: [],
      userInfo: '',
      replaceFields: { title: 'name', key: 'id', value: 'id', children: 'children' },
      columns,
      form: {
        startTime: '',
        endTime: '',
        alarmNum: '',
        page: 1,
        pageSize: 10,
        sortOrder: 'asc',
        alarmType: '1,2,3,4',
        username: '',
        macName: '',
        param: '',
      },
      disabledStatus: false,
      macfacData: [],
      colorList: colorList,
      visible: false,
      total: 0,
      jsonFields: buildJsonFields(columns),
      iconLoading: false,
      Loading: false,
      WebAllAlarmList: [],
      roleId: null,
      filterList: [],
      filterFlag: false,
      compname: '',
      formparams: '',
      handlingList: handlingList,
      resolveMethod: '',
      resolveId: null,
    };
  },
  created() {
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
    this.roleId = JSON.parse(localStorage.getItem('roleId'));
    this.form.username = this.userInfo.username;
    this.CompanyList();
    this.SelMacAlarmByParam();

    // if (this.roleId == 3) {
    //   this.WebAllAlarm();
    // } else {
    //   this.SelMacAlarmByParam();
    // }
  },
  methods: {
    // 数控厂报警历史
    WebAllAlarm() {
      this.Loading = true;
      api.WebAllAlarm().then((res) => {
        this.Loading = false;
        this.WebAllAlarmList = res.Data;
        this.data = this.WebAllAlarmList.slice(0, 10);
        this.total = res.Data.length;
        this.form.page = 1;
      });
    },
    // 分页
    changepage(page, size) {
      // debugger
      //    if( this.roleId==3){
      //      let index=(page-1)*10
      //      let end=((page-1)*10)+10

      //       if(this.filterFlag){
      //    this.data=this.filterList.slice(index,end);
      //       }else{
      //         this.data=this.WebAllAlarmList.slice(index,end);
      //       }
      // }else{
      // this.form.page = page;
      // this.SelMacAlarmByParam();
      // }

      this.form.page = page;
      this.SelMacAlarmByParam();
    },

    async CompanyList() {
      const res = await eapi.CompanyList({ Username: this.userInfo.username });
      if (res.MsgCode != 0) {
        return;
      }
      this.macfacData = res.Data;
    },
    filterAlarmlsit() {
      // 报警类型
      let WebAllAlarmList = [...this.WebAllAlarmList];
      WebAllAlarmList = WebAllAlarmList.filter((item) => this.form.alarmType.indexOf(item.alarmtype) >= 0);
      // 时间startTime: "",
      // endTime: "",
      // alarmNum: "",

      if (this.form.startTime || this.form.endTime) {
        let start = new Date(this.form.startTime);
        let endTime = new Date(this.form.endTime);
        if (start > endTime) {
          this.$message.info('开始时间必须小于结束时间');
        }
        WebAllAlarmList = WebAllAlarmList.filter(
          (item) => start < new Date(item.uploadtime) && new Date(item.uploadtime) < endTime
        );
      } else {
        WebAllAlarmList = WebAllAlarmList.filter((item) => new Date(item.uploadtime) <= new Date());
      }
      WebAllAlarmList = WebAllAlarmList.filter((item) => item.alarmNum.indexOf(this.form.alarmNum) >= 0);
      if (this.compname == '全部') {
        WebAllAlarmList = WebAllAlarmList.filter((item) => item.alarmNum.indexOf('') >= 0);
      } else {
        WebAllAlarmList = WebAllAlarmList.filter((item) => item.name.indexOf(this.compname) >= 0);
      }
      WebAllAlarmList = WebAllAlarmList.filter((item) => item.macnumb.indexOf(this.formparams) >= 0);

      WebAllAlarmList = WebAllAlarmList.filter((item) => item.alarmdata.indexOf(this.formparams) >= 0);
      this.filterList = WebAllAlarmList;
      this.form.page = 1;
      this.data = this.filterList.slice(0, 10);
      this.total = WebAllAlarmList.length;
      this.filterFlag = true;
    },
    handlequery() {
      this.SelMacAlarmByParam();
    },
    async SelMacAlarmByParam() {
      let parames = { ...this.form };
      if (!this.form.compId) {
        parames = { ...this.form, compId: this.userInfo.compid };
      } else {
        parames = { ...this.form };
      }

      this.Loading = true;
      const res = await api.SelMacAlarmByParamAndCompanyId(parames);
      if (res.total) {
        this.Loading = false;
        this.data = res.rows;
        this.total = res.total;
      } else {
        this.Loading = false;
        this.data = [];
        this.total = 0;
      }
    },
    clickalarmType(i) {
      if (this.disabledStatus === false) {
        let index = this.form.alarmType.indexOf(i);
        if (index >= 0) {
          //有就取消
          let str = index == 0 ? i : ',' + i;
          this.form.alarmType = this.form.alarmType.replace(str, '');
        } else {
          this.form.alarmType = index == 0 ? this.form.alarmType : this.form.alarmType + ',' + i;
        }

        this.form.page = 1;
        this.form.param = '';
        debounce(() => {
          this.SelMacAlarmByParam();
        }, 1000);
      } else {
        this.$message.error('正在导出中，请稍后');
      }
    },
    hideModal() {
      let params = {
        id: this.resolveId,
        resolveMethod: this.resolveMethod,
      };
      api.UpdateWebMacAlarmResolve(params).then((res) => {
        console.log(res);
        if (res.MsgCode == 0) {
          this.$message.info('处理成功');
          this.SelMacAlarmByParam();
        } else {
          this.$message.error(res.MsgDesc);
        }
      });
      this.visible = false;
    },
    toProcess(data) {
      this.resolveId = data.id;
      this.visible = true;
    },
    // handleChange() {},
    onChangeEnd(date, dateString) {
      this.form.endTime = dateString;
    },
    onChangestart(date, dateString) {
      this.form.startTime = dateString;
    },
    handleSubmit() {},
    // 获取需要导出的数据
    async getDownloadData() {
      let _this = this;
      _this.iconLoading = true;
      _this.disabledStatus = true;
      let total = _this.total;
      // 单条数据
      const Single = await _this.buildDownloadLists({ pageNum: 1, pageSize: 10 });
      // 单条数据 大小
      let SingleSize = computeData(Single[0]);

      // 限制总大小
      let main = 20 * 1024 * 1024;
      // 可导出数量
      let num = Math.ceil(main / SingleSize);
      // 最大总页数
      let pageSize = 300;
      let MaxLength = Math.ceil(num / pageSize);
      let length = 0;
      // 判断当前后台接口返回的条数
      if (total > num) {
        length = MaxLength;
      } else {
        length = Math.ceil(total / pageSize);
      }
      let newLists = [];
      for (let i = 1; i <= length; i++) {
        let lists = await this.buildDownloadLists({
          pageNum: i,
          pageSize: pageSize,
        });
        newLists.push(lists);
      }
      _this.iconLoading = false;
      _this.disabledStatus = false;
      return [].concat(...newLists);
    },

    async buildDownloadLists(parames) {
      let _this = this;
      let { pageNum, pageSize } = parames;
      // (_this.form.pageSize = pageSize), (_this.form.page = pageNum);
      let _parames = {};
      if (!_this.form.compId) {
        _parames = { ..._this.form, pageSize, page: pageNum, compId: _this.userInfo.compid };
      } else {
        _parames = { ..._this.form, pageSize, page: pageNum };
      }
      const res = await api.SelMacAlarmByParamAndCompanyId(_parames);
      if (!res.total) {
        return [];
      } else {
        return res.rows;
      }
    },
  },
};
</script>
<style scoped lang="less">
@import 'index.less';
</style>
